package com.ruoyi.standingbook.extermination.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.asset.extermination.constant.DisinfectionDirtConstant;
import com.ruoyi.asset.homepage.constant.StatusConstant;
import com.ruoyi.asset.homepage.enums.ServiceTypeEnum;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.domain.vo.ExterminationErecordVo;
import com.ruoyi.common.domain.vo.StatisticsExterminationVo;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.standingbook.extermination.domain.Extermination;
import com.ruoyi.standingbook.extermination.domain.bo.ExterminationBo;
import com.ruoyi.standingbook.extermination.domain.bo.ExterminationPicBo;
import com.ruoyi.standingbook.extermination.domain.vo.ExterminationImportDetailVo;
import com.ruoyi.standingbook.extermination.domain.vo.ExterminationPicVo;
import com.ruoyi.standingbook.extermination.domain.vo.ExterminationVo;
import com.ruoyi.standingbook.extermination.mapper.ExterminationMapper;
import com.ruoyi.standingbook.extermination.service.IExterminationService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 四害消杀Service业务层处理
 *
 * @author cc
 * @date 2023-04-30
 */
@RequiredArgsConstructor
@Service
public class ExterminationServiceImpl implements IExterminationService {

    private final ExterminationMapper baseMapper;
    private final ISysDictDataService sysDictDataService;

    /**
     * 查询四害消杀
     */
    @Override
    public ExterminationVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询四害消杀列表
     */
    @Override
    public TableDataInfo<ExterminationVo> queryPageList(ExterminationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Extermination> lqw = buildQueryWrapper(bo);
        Page<ExterminationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询四害消杀列表
     */
    @Override
    public List<ExterminationVo> queryList(ExterminationBo bo) {
        LambdaQueryWrapper<Extermination> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询Excel四害消杀列表
     */
    @Override
    public List<ExterminationVo> queryExcelList(ExterminationBo bo) {
        LambdaQueryWrapper<Extermination> lqw = buildExcelQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Extermination> buildQueryWrapper(ExterminationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Extermination> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), Extermination::getItemName, bo.getItemName());
        lqw.eq(StringUtils.isNotBlank(bo.getExterminationCategory()), Extermination::getExterminationCategory, bo.getExterminationCategory());
        lqw.like(StringUtils.isNotBlank(bo.getLocation()), Extermination::getLocation, bo.getLocation());
        lqw.eq(bo.getServiceType() != null, Extermination::getServiceType, bo.getServiceType());
        lqw.eq(bo.getFrequency() != null, Extermination::getFrequency, bo.getFrequency());
        lqw.eq(bo.getThisMonthTotalFrequency() != null, Extermination::getThisMonthTotalFrequency, bo.getThisMonthTotalFrequency());
        lqw.eq(bo.getArea() != null, Extermination::getArea, bo.getArea());
        lqw.eq(bo.getDosage() != null, Extermination::getDosage, bo.getDosage());
        lqw.eq(bo.getThisMonthTotalDosage() != null, Extermination::getThisMonthTotalDosage, bo.getThisMonthTotalDosage());
        lqw.eq(StringUtils.isNotBlank(bo.getExterminationUser()), Extermination::getExterminationUser, bo.getExterminationUser());
        lqw.eq(StringUtils.isNotBlank(bo.getPhoneNumber()), Extermination::getPhoneNumber, bo.getPhoneNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getUsingEquipment()), Extermination::getUsingEquipment, bo.getUsingEquipment());
        lqw.eq(StringUtils.isNotBlank(bo.getExterminationMethod()), Extermination::getExterminationMethod, bo.getExterminationMethod());
        lqw.eq(StringUtils.isNotBlank(bo.getAssignmentContent()), Extermination::getAssignmentContent, bo.getAssignmentContent());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Extermination::getStatus, bo.getStatus());
        lqw.between(params.get("beginDate") != null && params.get("endDate") != null,
            Extermination::getDate ,params.get("beginDate"), params.get("endDate"));
        lqw.orderByDesc(Extermination::getCreateTime);
        lqw.orderByDesc(Extermination::getDate);
        return lqw;
    }

    private LambdaQueryWrapper<Extermination> buildExcelQueryWrapper(ExterminationBo bo) {
        Map<String, Object> params = bo.getParams();
        if(params.get("endDate") == null){
            params.put("endDate", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
        }
        LambdaQueryWrapper<Extermination> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getExterminationCategory()), Extermination::getExterminationCategory, bo.getExterminationCategory());
        lqw.eq(params.get("endDate") != null, Extermination::getDate , params.get("endDate").toString().substring(0,10));
        lqw.orderByDesc(Extermination::getCreateTime);
        lqw.orderByDesc(Extermination::getDate);
        return lqw;
    }


    /**
     * 新增四害消杀
     */
    @Override
    public Boolean insertByBo(ExterminationBo bo) {
        Extermination add = BeanUtil.toBean(bo, Extermination.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改四害消杀
     */
    @Override
    public Boolean updateByBo(ExterminationBo bo) {
        Extermination update = BeanUtil.toBean(bo, Extermination.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Extermination entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除四害消杀
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量插入
     */
    @Override
    public Boolean batchInsert(List<ExterminationImportDetailVo> voList) {
        if (null != voList && !voList.isEmpty()) {
            Date date = voList.get(0).getDate();
            date.setHours(0);
            date.setMinutes(0);
            date.setSeconds(0);
            LambdaQueryWrapper<Extermination> lqw = Wrappers.lambdaQuery();
            lqw.eq(Extermination::getDate, date);
            this.baseMapper.delete(lqw);
        }

        List<Extermination> list = BeanCopyUtils.copyList(voList, Extermination.class);
        list.forEach(e -> {
            e.setId(null);
            e.restBase();
        });
        return this.baseMapper.insertBatch(list);
    }

    /**
     * 获取四害消杀电子档案信息
     *
     * @param bo
     * @return
     */
    public ExterminationErecordVo getExterminationErecordInfo(ExterminationBo bo) {
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(bo.getDate())) {
            throw new RuntimeException("日期不能为空");
        }
        ExterminationErecordVo eev = new ExterminationErecordVo();
        List<StatisticsExterminationVo> todayExterminationList = baseMapper.statisticsTodayExterminationList();
        eev.setExterminationTodayList(todayExterminationList);   //统计今天消杀情况分组列表
        List<StatisticsExterminationVo> monthExterminationList = baseMapper.statisticsMonthExterminationList(bo);
        eev.setExterminationMonthList(monthExterminationList); //统计指定月消杀情况分组列表

        Long totalTodayFrequency = 0L; //合计今日消杀频率
        Double totalTodayArea = 0d;    //合计今日消杀面积（㎡）
        Double totalTodayDosage = 0d;  //合计今日用药量
        Long totalThisMonthFrequency = 0L; //合计本月消杀频率
        Double totalThisMonthArea = 0d; //合计本月消杀面积（㎡）
        Double totalThisMonthDosage = 0d; //合计本月用药量
        boolean exterminationCategoryFlag1 = false;
        boolean exterminationCategoryFlag2 = false;
        boolean exterminationCategoryFlag3 = false;
        for (StatisticsExterminationVo ev : todayExterminationList) {
            totalTodayFrequency += ev.getFrequency();
            totalTodayArea += ev.getArea();
            totalTodayDosage += ev.getDosage();
            if (ev.getExterminationCategory().equals("1")) {
                exterminationCategoryFlag1 = true;
            } else if (ev.getExterminationCategory().equals("2")) {
                exterminationCategoryFlag2 = true;
            } else if (ev.getExterminationCategory().equals("3")) {
                exterminationCategoryFlag3 = true;
            }
        }
        //合并月数据到今日统计列表
        for (StatisticsExterminationVo sev : monthExterminationList) {
            for (StatisticsExterminationVo sev2 : todayExterminationList) {
                if (sev.getExterminationCategory().equals(sev2.getExterminationCategory())) {
                    sev2.setThisMonthFrequency(sev.getFrequency() == null ? 0L : sev.getFrequency());
                    sev2.setThisMonthArea(sev.getArea() == null ? 0d : sev.getArea());
                    sev2.setThisMonthDosage(sev.getDosage() == null ? 0d : sev.getDosage());
                    break;
                }
            }
        }

        if (!exterminationCategoryFlag1) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭鼠");
            sev.setExterminationCategory("1");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            todayExterminationList.add(sev);
        }
        if (!exterminationCategoryFlag2) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭蚊蝇");
            sev.setExterminationCategory("2");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            todayExterminationList.add(sev);
        }
        if (!exterminationCategoryFlag3) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭蟑");
            sev.setExterminationCategory("3");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            todayExterminationList.add(sev);
        }


        exterminationCategoryFlag1 = false;
        exterminationCategoryFlag2 = false;
        exterminationCategoryFlag3 = false;
        for (StatisticsExterminationVo ev : monthExterminationList) {
            totalThisMonthFrequency += ev.getFrequency();
            totalThisMonthArea += ev.getArea();
            totalThisMonthDosage += ev.getDosage();
            if (ev.getExterminationCategory().equals("1")) {
                exterminationCategoryFlag1 = true;
            } else if (ev.getExterminationCategory().equals("2")) {
                exterminationCategoryFlag2 = true;
            } else if (ev.getExterminationCategory().equals("3")) {
                exterminationCategoryFlag3 = true;
            }
        }
        if (!exterminationCategoryFlag1) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭鼠");
            sev.setExterminationCategory("1");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            monthExterminationList.add(sev);
        }
        if (!exterminationCategoryFlag2) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭蚊蝇");
            sev.setExterminationCategory("2");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            monthExterminationList.add(sev);
        }
        if (!exterminationCategoryFlag3) {
            StatisticsExterminationVo sev = new StatisticsExterminationVo();
            sev.setExterminationCategoryName("灭蟑");
            sev.setExterminationCategory("3");
            sev.setFrequency(0L);
            sev.setArea(0d);
            sev.setArea(0d);
            monthExterminationList.add(sev);
        }

        eev.setTotalTodayFrequency(totalTodayFrequency);
        eev.setTotalTodayArea(totalTodayArea);
        eev.setTotalTodayDosage(totalTodayDosage);
        eev.setTotalThisMonthFrequency(totalThisMonthFrequency);
        eev.setTotalThisMonthArea(totalThisMonthArea);
        eev.setTotalThisMonthDosage(totalThisMonthDosage);
        return eev;
    }

    @Override
    public List<ExterminationPicVo> getDrugPicByDate(String date) {
        List<ExterminationPicBo> exterminationPicBos = baseMapper.selectPicByDate(date);
        List<ExterminationPicVo> pics = new ArrayList<>();
        exterminationPicBos.forEach(e->{
            if (StringUtils.isNotBlank(e.getPic1())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic1());
                pics.add(exterminationPicVo);
            }
            if (StringUtils.isNotBlank(e.getPic2())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic2());
                pics.add(exterminationPicVo);
            }
        });
        return pics;
    }

    @Override
    public List<ExterminationPicVo> getBeforePicByDate(String date) {
        List<ExterminationPicBo> exterminationPicBos = baseMapper.selectPicByDate(date);
        List<ExterminationPicVo> pics = new ArrayList<>();
        exterminationPicBos.forEach(e->{
            if (StringUtils.isNotBlank(e.getPic3())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic3());
                pics.add(exterminationPicVo);
            }
            if (StringUtils.isNotBlank(e.getPic4())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic4());
                pics.add(exterminationPicVo);
            }
        });
        return pics;
    }

    @Override
    public List<ExterminationPicVo> getCoursePicByDate(String date) {
        List<ExterminationPicBo> exterminationPicBos = baseMapper.selectPicByDate(date);
        List<ExterminationPicVo> pics = new ArrayList<>();
        exterminationPicBos.forEach(e->{
            if (StringUtils.isNotBlank(e.getPic5())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic5());
                pics.add(exterminationPicVo);
            }
            if (StringUtils.isNotBlank(e.getPic6())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic6());
                pics.add(exterminationPicVo);
            }
        });
        return pics;
    }

    @Override
    public List<ExterminationPicVo> getAfterPicByDate(String date) {
        List<ExterminationPicBo> exterminationPicBos = baseMapper.selectPicByDate(date);
        List<ExterminationPicVo> pics = new ArrayList<>();
        exterminationPicBos.forEach(e->{
            if (StringUtils.isNotBlank(e.getPic7())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic7());
                pics.add(exterminationPicVo);
            }
            if (StringUtils.isNotBlank(e.getPic8())){
                ExterminationPicVo exterminationPicVo = new ExterminationPicVo();
                exterminationPicVo.setPic(e.getPic8());
                pics.add(exterminationPicVo);
            }
        });
        return pics;
    }

    @Override
    public int getSumByDate(String date) {
        List<Integer> numSum = baseMapper.selectSumByDate(date, StatusConstant.FINISHED);
        return numSum.stream().reduce(Integer::sum).orElse(0);
    }

    @Override
    public List<ExterminationVo> queryListByDate(String date) {
        ArrayList<ExterminationVo> list = new ArrayList<>();
        LambdaQueryWrapper<Extermination> lqw = Wrappers.lambdaQuery();
        lqw.eq(Extermination::getDate,date);
        lqw.orderByDesc(Extermination::getArea);
        List<ExterminationVo> exterminationVos = baseMapper.selectVoList(lqw);
        exterminationVos.forEach(e->{
            e.setServiceTypeName(ServiceTypeEnum.EXTERMINATION.getTypeName());
            ExterminationVo exterminationVo = new ExterminationVo();
            BeanCopyUtils.copy(e,exterminationVo);
            String exterminationType = sysDictDataService.selectDictLabel(DisinfectionDirtConstant.EXTERMINATION_TYPE, exterminationVo.getExterminationCategory());
            if (StringUtils.isNotBlank(exterminationType)){
                exterminationVo.setExterminationCategory(exterminationType);
            }
            list.add(exterminationVo);
        });
        return list;
    }

    @Override
    public Integer getNumByYearToNow() {
        return baseMapper.statisticsNumYearToNow();
    }
}
